﻿using System;
using System.Web;
using System.Web.UI.WebControls;
using Core.AdminGroupMenuPermission;
using Core.Authenticated;
using Core.Library;
using DataObject;
using DataObject.Cache;
using DataObject.Members;

namespace CMS.Controls.Members
{
    public partial class TopVoteManager : AuthenticatedControl
    {
        #region Variables

        protected string Tab;
        protected string KName;
        protected string KEmail;
        protected string Url;
        protected int PageIndex;
        protected int PageSize;
        protected int Round1;
        protected int Round2;
        protected int Round3;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            Tab = Utils.GetIdFromRequestString(Utils.Tab, string.Empty);

            if (string.IsNullOrEmpty(Tab))
                Response.Redirect(UrlHelpers.ListTab(cControl.AdminMenuId, MemberRound.Round1.ToString()));

            KName = Utils.GetIdFromRequestString(Utils.KName, string.Empty);
            KEmail = Utils.GetIdFromRequestString(Utils.KEmail, string.Empty);
            PageIndex = Utils.GetIdFromRequestString(Utils.PageIndex, SettingValues.PageIndex);
            PageSize = Utils.GetIdFromRequestString(Utils.PageSize, ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
            Url = HttpUtility.UrlEncode(Request.Url.ToString());

            if (!IsPostBack)
            {
                InitArticle();
                ListData();
                GetStatistics();
            }
        }

        #region Statistics

        private void GetStatistics()
        {
            Round1 = MembersController.Members_GetStatistic((int)MemberRound.Round1, (int)MemberStatus.IsPublished);
            Round2 = MembersController.Members_GetStatistic((int)MemberRound.Round2, (int)MemberStatus.IsPublished);
            Round3 = MembersController.Members_GetStatistic((int)MemberRound.Round3, (int)MemberStatus.IsPublished);
        }

        #endregion

        #region Bind Data

        private void InitArticle()
        {
            var isShowPublished = false;

            var adminGroupMenuPermission =
                    AdminGroupMenuPermissionController.AdminGroupMenuPermission_GetBy_AdminUserId_AdminMenuId(CurrentUser.AdminUserId, cControl.AdminMenuId);
            if (adminGroupMenuPermission.Count > 0)
            {
                foreach (var agmp in adminGroupMenuPermission)
                {
                    isShowPublished = StatusHelper.IsChecked(agmp.Status, (int)PermissionObject.CanPublish);
                }
            }

            hfTab.Value = Tab;
            if (!string.IsNullOrEmpty(hfTab.Value))
            {
                switch (hfTab.Value)
                {
                    case "Round1":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.Round1).ToString();
                        btnSave.Visible = isShowPublished;
                        break;
                    case "Round2":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.Round2).ToString();
                        btnSave.Visible = isShowPublished;
                        break;
                    case "Round3":
                        hfStatus.Value = ((int)MemberStatus.IsPublished).ToString();
                        hfRound.Value = ((int)MemberRound.Round3).ToString();
                        btnSave.Visible = isShowPublished;
                        break;
                }
            }
            else
            {
                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Không lấy được dữ liệu.", MessageType.Failure);
            }
        }

        private void ListData()
        {
            var currentKName = UnicodeUtility.DecodeFrom64(KName);
            if (currentKName.IndexOf("Tên đầy đủ") != -1)
                currentKName = string.Empty;
            var currentKEmail = UnicodeUtility.DecodeFrom64(KEmail);
            if (currentKEmail.IndexOf("Email") != -1)
                currentKEmail = string.Empty;

            lvList.DataSource = MembersController.Members_GetListByTypeByStatusPaging(currentKName, currentKEmail,
                                                                                ConvertUtility.ConvertTo<int>(hfRound.Value),
                                                                                ConvertUtility.ConvertTo<int>(hfStatus.Value),
                                                                                PageIndex, PageSize, string.Format("{2} DESC , {0}{1} DESC", Constants.Table_Members.Vote, ConvertUtility.ConvertTo<int>(hfRound.Value), Constants.Table_Members.isCheatVote));
            lvList.DataBind();

            var totalRecords = MembersController.Members_Count(currentKName, currentKEmail,
                                                                                ConvertUtility.ConvertTo<int>(hfRound.Value),
                                                                                ConvertUtility.ConvertTo<int>(hfStatus.Value));

            txtKName.Value = currentKName;
            txtKEmail.Value = currentKEmail;
            ddlPageSize.SelectedValue = PageSize.ToString();
            ltPager.Text = PagerUtility.PageLinks(PageIndex, PageSize, totalRecords, 5,
                                UrlHelpers.ListSearch(cControl.AdminMenuId, currentKName, currentKEmail, hfTab.Value, "{0}", PageSize));

        }

        protected void lvList_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var round = ConvertUtility.ConvertTo<int>(hfRound.Value);
                switch (round)
                {
                    case 1:
                        e.Item.FindControl("phVote1").Visible = true;
                        break;
                    case 2:
                        e.Item.FindControl("phVote2").Visible = true;
                        break;
                    case 3:
                        e.Item.FindControl("phVote3").Visible = true;
                        break;
                }
            }
        }

        #endregion

        #region Action

        protected void BtnSave(object sender, EventArgs e)
        {
            try
            {
                var round = ConvertUtility.ConvertTo<int>(hfRound.Value);
                var voteName = "txtVote" + round;
                foreach (ListViewDataItem lvi in lvList.Items)
                {
                    var cbItem = (CheckBox)lvi.FindControl("cbItem");
                    if (cbItem == null || !cbItem.Checked) continue;

                    var txtVote = (TextBox)lvi.FindControl(voteName);
                    if (txtVote == null) continue;

                    var txtCheat = (TextBox)lvi.FindControl("txtCheat");
                    if (txtCheat == null) continue;

                    var id = ConvertUtility.ConvertTo<int>(lvList.DataKeys[lvi.DisplayIndex].Value);
                    if (id > 0)
                        MembersController.Members_Update_Vote_Cheat(id, round, ConvertUtility.ConvertTo<int>(txtVote.Text), ConvertUtility.ConvertTo<short>(txtCheat.Text));
                }

                ltMessage.Text = MessageUtility.ShowMessage(string.Empty, "Sửa thành công.", MessageType.Success);
                CacheController.RemoveCachePort(Constants.ManagerCacheGroup.User);
                ListData();
                GetStatistics();
            }
            catch (Exception ex)
            {

                ltMessage.Text = MessageUtility.ShowMessage("Lỗi", ex.Message, MessageType.Failure);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            RedirectLink(PageSize);
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            RedirectLink(ConvertUtility.ConvertTo<int>(ddlPageSize.SelectedValue));
        }

        public void RedirectLink(int currentPageSize)
        {

            var kName = txtKName.Value.IndexOf("Tên đầy đủ") != -1 ? string.Empty : txtKName.Value;
            var kEmail = txtKEmail.Value.IndexOf("Email") != -1 ? string.Empty : txtKEmail.Value;

            Response.Redirect(UrlHelpers.ListSearch(cControl.AdminMenuId,
                                                        UnicodeUtility.EncodeTo64UTF8(kName),
                                                        UnicodeUtility.EncodeTo64UTF8(kEmail),
                                                        hfTab.Value,
                                                        SettingValues.PageIndex.ToString(), currentPageSize));
        }

        #endregion
    }
}